# 封装购物车合并
import json

from django_redis import get_redis_connection

from utils.cookiesecret import CookieSecret
def merge_cart_cookie_to_redis(request, user, response):
    cookie_str = request.COOKIES.get('carts')

    if cookie_str:
        cookie_dict = CookieSecret.loads(cookie_str)
    else:
        return response

    redis_client = get_redis_connection('carts')
    redis_data = redis_client.hgetall(user.id)
    redis_dict = {int(data[0].decode()):json.loads(data[1].decode()) for data in redis_data.items}

    redis_dict.update(cookie_dict)
    for sku_id in redis_dict.keys():
        redis_client.hset(user.id, sku_id, json.dumps(redis_dict[sku_id]))

    response.delete_cookie('carts')

    return response
